package ro.sobis.repetor;

import java.net.*;
import  java.io.*;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class ForwardConexiune implements Runnable{
	private Log log = LogFactory.getLog(ForwardConexiune.class);
	Socket inSocket = null;
	Socket outSocket = null;
	Thread myThread = null;
	private InputStream socketInput = null;
	private OutputStream socketOutput = null;
	private String id="";

	public ForwardConexiune(Socket inSocket, Socket outSocket) {
		
		this.inSocket = inSocket;
		this.outSocket = outSocket;
		try {
			socketInput = inSocket.getInputStream();
			socketOutput = outSocket.getOutputStream();
		}
		catch(Exception e) {
			log.error(id+ " Exceptie la crearea stream-urilor:"+e);
			
		}

		myThread = new Thread(this);
		myThread.start();
	}
	
	public ForwardConexiune(String id,Socket inSocket, Socket outSocket)
	{
		this(inSocket,outSocket);
		this.id=id;
	}

	public void run() {
		int bytesRead=0;
		int bufLen = 512;
		byte buf[]= new byte[bufLen];

				
		while(true) {

			try {
				bytesRead = socketInput.read(buf,0,bufLen);
				if(bytesRead > 0) {
					/*	String readString = new String(buf,0,bytesRead);
						System.err.println(System.currentTimeMillis()+readString);*/
					System.err.println(id);
					socketOutput.write(buf,0,bytesRead);
					socketOutput.flush();
				}
				else if(bytesRead < 0) {
					log.error(id+" Socket inchis :"+inSocket);
					return;
				}
				else {
					log.error(id+" Socket-ul a returnat 0 bytes in loc sa ramana blocat..."+inSocket);
					return;
				}

			}
			catch(Exception e) {
				log.error(id+e.getMessage());
				return;
			}
			
			

		}
	}

}